import { BASE_URL } from '@/Requset/request'

export function requestWithAuth(options) {
  return new Promise((resolve, reject) => {
    let token = uni.getStorageSync('token') || ''
    options.header = options.header || {}
    options.header.token = token

    // 自动拼接基础域名
    if (!/^https?:\/\//.test(options.url)) {
      options.url = BASE_URL + options.url.replace(/^\/+/, '')
    }

    uni.request({
      ...options,
      success: async (res) => {
        // 如果token失效，尝试刷新token
        if (res.statusCode === 401) {
          const refreshRes = await refreshToken()
          if (refreshRes && refreshRes.status === 0 && refreshRes.token) {
            // 刷新成功，重试原请求
            uni.setStorageSync('token', refreshRes.token)
            options.header.token = refreshRes.token
            uni.request({
              ...options,
              success: resolve,
              fail: reject
            })
          } else {
            // 刷新失败，跳转登录
            uni.removeStorageSync('token')
            uni.removeStorageSync('refreshToken')
            uni.showToast({ title: '请重新登录', icon: 'none' })
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/Login/Login' })
            }, 1000)
            reject(res)
          }
        } else {
          resolve(res)
        }
      },
      fail: reject
    })
  })
}

// 刷新token方法
function refreshToken() {
  const refreshToken = uni.getStorageSync('refreshToken')
  if (!refreshToken) return Promise.resolve(null)
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + 'api/refreshToken', // 修改为正确的刷新token接口
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { refreshToken }, // 参数名为 refreshToken
      success: (res) => resolve(res.data),
      fail: reject
    })
  })
}

export { refreshToken }